package com.xnx3.banmahuishou.wangge.controller;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.ObjectUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alipay.api.domain.HuanxuTradeOrderQueryModel;
import com.xnx3.DateUtil;
import com.xnx3.banmahuishou.core.entity.OrderEvaluationRecord;
import com.xnx3.banmahuishou.core.entity.Qishou;
import com.xnx3.banmahuishou.core.entity.TransferOrderRecord;
import com.xnx3.banmahuishou.core.entity.Wangge;
import com.xnx3.banmahuishou.core.entity.WanggeSettime;
import com.xnx3.banmahuishou.core.entity.WeixinPublicQishouOpenid;
import com.xnx3.j2ee.generateCache.BaseGenerate;
import com.xnx3.j2ee.service.SqlService;
import com.xnx3.j2ee.util.ActionLogUtil;
import com.xnx3.j2ee.util.Page;
import com.xnx3.j2ee.util.Sql;
import com.xnx3.wangmarket.shop.core.entity.Order;
import com.xnx3.wangmarket.shop.core.entity.OrderGoods;
import com.xnx3.wangmarket.shop.core.service.OrderService;
import com.xnx3.wangmarket.shop.core.service.OrderStateLogService;
import com.xnx3.wangmarket.shop.core.vo.OrderVO;
import com.xnx3.wangmarket.shop.store.vo.OrderListVO;
import com.xnx3.weixin.WeiXinUtil;

/**
 * 订单管理
 * @author 王晓龙
 */
@Controller(value="BanmahuishouWanggeOrderController")
@RequestMapping("/wangge/order/")
public class OrderController extends BaseController  {
	@Resource
	private SqlService sqlService;
	@Resource
	private OrderService orderService;
	@Resource
	private OrderStateLogService orderStateLogService;

	/**
	 * 查看订单列表
	 * @param startTime 日期范围的开始时间
	 * @param endTime 日期范围的结束时间
	 * @author 王晓龙
	 */
	@ResponseBody
	@RequestMapping(value="list.json", method = {RequestMethod.POST})
	public OrderListVO list(HttpServletRequest request,Model model,
			@RequestParam(value = "startTime", required = false, defaultValue = "0") int startTime,
			@RequestParam(value = "endTime", required = false, defaultValue = "0") int endTime) {
		OrderListVO vo = new OrderListVO();
		//创建Sql
		Sql sql = new Sql(request);
		//配置查询那个表
		sql.setSearchTable("shop_order");

		//配置按某个字端搜索内容
		sql.setSearchColumn(new String[] {"qishou_name=","no","phone=","state="});
		sql.appendWhere("((reserve_end_time > " + DateUtil.timeForUnix10() + " AND state = " + Order.STATE_DAIQUHUO + ") OR state = " + Order.STATE_FINISH + " OR state = " + Order.STATE_CANCEL + " OR state = " + Order.STATE_EVALUATED + ") AND wangge_userid = " + getUserId());
//		String addtime = request.getParameter("addtime");
//		//下单时间NaN拦截
//		if (StringUtils.hasLength(addtime) && Objects.equals(addtime, "NaN")) {
//			vo.setBaseVO(BaseVO.FAILURE,"下单时间错误,请刷新后重新选择");
//			return vo;
//		}
//		// 只传入开始时间
//		if (StringUtils.hasLength(addtime)) {
//			//传入指定的时间返回明天00:00:00的时间戳
//			int dayEndTime = DateUtil.getDateZeroTime(Integer.valueOf(addtime))+24*60*60;
//			sql.appendWhere("addtime >= " + addtime + " AND addtime < " + dayEndTime);
//		}
		//时间查询条件
		if (startTime > 0) {
			sql.appendWhere(" addtime >= " + startTime);
		}
		if (endTime > 0) {
			//传入指定的时间返回明天00:00:00的时间戳
			int dayEndTime = DateUtil.getDateZeroTime(endTime)+24*60*60;
			sql.appendWhere(" addtime <= " + dayEndTime);
		}
		// 查询数据表的记录总条数
		int count = sqlService.count("shop_order", sql.getWhere());
		
		// 配置每页显示15条
		Page page = new Page(count, 15, request);
		// 查询出总页数
		sql.setSelectFromAndPage("SELECT * FROM shop_order ", page);
		//选择排序方式 当用户没有选择排序方式时，系统默认降序排序
		sql.setDefaultOrderBy("state ASC");
		// 按照上方条件查询出该实体总数 用集合来装
		List<Order> list = sqlService.findBySql(sql,Order.class);
		
		// 将信息保存到vo中
		vo.setList(list);
		vo.setPage(page);
		//日志记录
		ActionLogUtil.insert(request, getUserId(), "查看订单列表");
		return vo;
	}
	
	/**
	 * 查看异常订单列表
	 * @author 王晓龙
	 */
	@ResponseBody
	@RequestMapping(value="notTakenList.json", method = {RequestMethod.POST})
	public OrderListVO notTakenList(HttpServletRequest request,Model model) {
		OrderListVO vo = new OrderListVO();
		//创建Sql
		Sql sql = new Sql(request);
		//配置查询那个表
		sql.setSearchTable("shop_order");
		//配置按某个字端搜索内容
		sql.setSearchColumn(new String[] {"qishou_name"});
		// 状态是待接单  或者 状态是待取货 且 已超过预约时间
		sql.appendWhere("((state = " + Order.STATE_DAIJIEDAN + " AND qishou_id IS  NULL) OR (reserve_end_time < " + DateUtil.timeForUnix10() + " AND state = " + Order.STATE_DAIQUHUO + ")) AND wangge_userid = " +getUserId());
		// 查询数据表的记录总条数
		int count = sqlService.count("shop_order", sql.getWhere());
		// 配置每页显示15条
		Page page = new Page(count, 15, request);
		// 查询出总页数
		sql.setSelectFromAndPage("SELECT * FROM shop_order ", page);
		//选择排序方式 当用户没有选择排序方式时，系统默认降序排序
		sql.setDefaultOrderBy("id DESC");
		// 按照上方条件查询出该实体总数 用集合来装
		List<Order> list = sqlService.findBySql(sql,Order.class);
		// 将信息保存到vo中
		vo.setList(list);
		vo.setPage(page);

		//日志记录
		ActionLogUtil.insert(request, getUserId(), "查看订单列表");
		return vo;
	}

	/**
	 * 查看订单详情
	 * @author 王晓龙
	 * @param id 订单id
	 */
	@ResponseBody
	@RequestMapping(value="orderDetails.json", method = {RequestMethod.POST})
	public OrderVO orderDetails(Model model ,HttpServletRequest request,
							   @RequestParam(value = "id", required = false, defaultValue = "0") int id) {
		
		OrderVO vo = new OrderVO();
		if(id > 0) {
			//查到订单信息
			Order order = sqlService.findById(Order.class, id);
			//查看订单的商品信息
			String sql = "SELECT * FROM shop_order_goods WHERE orderid = " + id;
			List<OrderGoods> list = sqlService.findBySqlQuery(sql,OrderGoods.class);
			//查看订单评价记录
			OrderEvaluationRecord orderEvaluationRecord = sqlService.findById(OrderEvaluationRecord.class, id);
			
			vo.setGoodsList(list);
			vo.setOrder(order);
			vo.setOrderEvaluationRecord(orderEvaluationRecord);
			ActionLogUtil.insert(request, getUserId(), "查看订单ID为" + id+ "的详情");
			
		}
		return vo;
	}
	
	/**
	 * 给订单分配骑手
	 * @author 王晓龙
	 * @param inputOrder 接收参数的实体类
	 */
	@ResponseBody
	@RequestMapping(value="/save${api.suffix}",method = {RequestMethod.POST})
	public com.xnx3.j2ee.vo.BaseVO save(HttpServletRequest request,Order inputOrder) {
		
		Order order;
		//查询要分配骑手的订单信息
		order = sqlService.findById(Order.class, inputOrder.getId());
		if(order == null){
			return error("要分配骑手的订单不存在");
		}
		if(inputOrder.getQishouId() == null) {
			return error("请选择骑手");
		}
		if(inputOrder.getReserveStartTime() > inputOrder.getReserveEndTime()){
			return error("选择的预约结束时间不能大于预约开始时间");
		}
		if(inputOrder.getReserveStartTime() < DateUtil.timeForUnix10() || inputOrder.getReserveStartTime() == null) {
			return error("未选择预约开始时间或选择开始时间未大于当前时间");
		}
		if(inputOrder.getReserveEndTime() < DateUtil.timeForUnix10() || inputOrder.getReserveEndTime() == null) {
			return error("未选择预约结束时间或选择结束时间未大于当前时间");
		}
		// 查询网格的营业时间信息
		String sql = "SELECT * FROM laji_wangge_settime WHERE wangge_id = " + getUserId();
		WanggeSettime wanggeSettime = sqlService.findAloneBySqlQuery(sql, WanggeSettime.class);
		if (wanggeSettime != null) {
			// 取出休息日
			String restTime = wanggeSettime.getRestTime();
			String[] restTimes = restTime.split(",");
			// 预约日期
			Date date = new Date();
			date.setTime(inputOrder.getReserveStartTime() * 1000L);
			String weekName = getWeekOfDate(date);
			// 判断预约的那天是否休息日
			for (String string : restTimes) {
				if (ObjectUtils.equals(weekName, string)) {
					return error("今日休息，请选择其他时间段"); 
				}
			}
			// 取出营业时间,判断是否在其内
			// 营业开始时间(小时)
			Integer startTime = Integer.valueOf(DateUtil.intToString(wanggeSettime.getStartTime(), "HH"));
			// 营业结束时间(小时)
			Integer endTime = Integer.valueOf(DateUtil.intToString(wanggeSettime.getEndTime(), "HH"));
			// 预约开始时间(小时)
			Integer startTimeForUser = Integer.valueOf(DateUtil.intToString(inputOrder.getReserveStartTime(), "HH"));
			// 预约结束时间(小时)
			Integer endTimeForUser = Integer.valueOf(DateUtil.intToString(inputOrder.getReserveEndTime(), "HH"));
			// 营业开始时间(分钟)
			Integer startMin = Integer.valueOf(DateUtil.intToString(wanggeSettime.getStartTime(), "mm"));
			// 营业结束时间(分钟)
			Integer endMin = Integer.valueOf(DateUtil.intToString(wanggeSettime.getEndTime(), "mm"));
			// 预约开始时间(分钟)
			Integer startMinForUser = Integer.valueOf(DateUtil.intToString(inputOrder.getReserveStartTime(), "mm"));
			// 预约结束时间(分钟)
			Integer endMinForUser = Integer.valueOf(DateUtil.intToString(inputOrder.getReserveEndTime(), "mm"));
			if ((startTimeForUser <= startTime && startMinForUser < startMin) || startTimeForUser > endTime ) {
				return error("超出营业时间,请选择其他预约时间"); 
			}
			if ((endTimeForUser <= endTime && endMinForUser > endMin) || endTimeForUser > endTime  ) {
				return error("超出营业时间,请选择其他预约时间"); 
			}
			
		}
		//给实体赋值
		Qishou qishou = sqlService.findById(Qishou.class, inputOrder.getQishouId());
		TransferOrderRecord transferOrderRecord = new TransferOrderRecord();
		if(order.getQishouId() == null) {
			transferOrderRecord.setQishouName("订单无原骑手");
			transferOrderRecord.setQishouUserid(0);
		}else {
			transferOrderRecord.setQishouName(order.getQishouName());
			transferOrderRecord.setQishouUserid(order.getQishouId());
		}
		order.setQishouName(qishou.getName());
		order.setQishouId(qishou.getId());
		order.setQishouPhone(qishou.getPhone());
		order.setQishouHead(qishou.getHead());
		order.setReserveEndTime(inputOrder.getReserveEndTime());
		order.setReserveStartTime(inputOrder.getReserveStartTime());
		order.setState(Order.STATE_DAIQUHUO);
		//插入一条分配订单记录
		Wangge wangge = sqlService.findById(Wangge.class, getUserId());
		
		transferOrderRecord.setCreateTime(DateUtil.timeForUnix10());
		transferOrderRecord.setOrderId(inputOrder.getId());
		transferOrderRecord.setOrderNo(order.getNo());
		//将未更新的订单骑手id和名字插入到分配订单记录表
		transferOrderRecord.setReason("在" + DateUtil.intToString(DateUtil.timeForUnix10(),"yyyy-MM-dd HH:mm") + "异常订单分配给了，骑手：" + qishou.getName());
		transferOrderRecord.setWanggeUserid(wangge.getId());
		transferOrderRecord.setWanggeName(wangge.getName());
		transferOrderRecord.setXinqishouUserid(qishou.getId());
		transferOrderRecord.setXinqishouName(qishou.getName());
		
		//保存实体
		sqlService.save(transferOrderRecord);
		sqlService.save(order);
		// 发送公众号消息通知
		WeixinPublicQishouOpenid publicQishouOpenid = sqlService.findAloneByProperty(WeixinPublicQishouOpenid.class, "userid", order.getQishouId());
		// 公众号appid
		String appId = "wxbdb3e50bee354370";
		// 公众号appSecret
		String appSecret = "a982dbff8974eece711db294d8ca4026";
		String qishouOpenid = "oVtlg5CwVXVo1PiOVaFRlRt8MjwA";
		String publicTemplateId = "xDqqPgahOLmg1VjnL7740bd9P-X_7A85EiXrZWRtlGY";
		if (publicQishouOpenid != null) {
			qishouOpenid = publicQishouOpenid.getOpenid();
		}
		WeiXinUtil wx = new WeiXinUtil(appId, appSecret);
		Map<String, String> dataMap = new HashMap<String, String>();
		dataMap.put("first", "您有一个新订单,请及时查看");//标题
		dataMap.put("keyword1", order.getNo());//订单号
		dataMap.put("keyword2", order.getUsername());//客户姓名
		dataMap.put("keyword3", order.getAddress());//订单地址
		dataMap.put("keyword4", DateUtil.intToString(order.getReserveStartTime(), "yyyy-MM-dd HH:mm") + "~" + DateUtil.intToString(order.getReserveEndTime(), "HH:mm"));//预约时间
		dataMap.put("keyword5", "联系方式: " + order.getPhone());//其他信息
		dataMap.put("remark", "请注意查看新任务,务必在客户预约时间内上门取货");//备注

		com.xnx3.BaseVO baseVO = wx.sendTemplateMessage(publicTemplateId, qishouOpenid, dataMap,null , null);
		//日志记录
		ActionLogUtil.insertUpdateDatabase(request, inputOrder.getId(),"给Id为" + inputOrder.getId() + "的订单,分配骑手，订单信息是:" + order.toString());

		return success();
	}
	
	/**
	 * 动态生成所有的骑手名称js
	 * @param request
	 * @param response
	 */
	@ResponseBody
	@RequestMapping(value="/getQishouJs${api.suffix}",method = {RequestMethod.GET})
	public void getQishouJs(HttpServletRequest request,HttpServletResponse response) {
			// 获取当前网格下的列表
			String sql = "SELECT * FROM laji_qishou WHERE wangge_userid = " + getUserId() + " AND state = " + Qishou.STATE_NORMAL;
			List<Qishou> list = sqlService.findBySqlQuery(sql, Qishou.class);
			BaseGenerate generate = new BaseGenerate();
			generate.createCacheObject("qishou_id");
			for (int i = 0; i < list.size(); i++) {
				generate.cacheAdd(list.get(i).getId(), list.get(i).getName());
			}
			generate.addCommonJsFunction();
			//输出
			response.setCharacterEncoding("utf-8");//第一句，设置服务器端编码
			response.setContentType("text/html;charset=utf-8");//第二句，设置浏览器端解码
			try {
				response.getWriter().write(generate.content);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	
	/**
	 * 获取指定日期是星期几<br>
	 *
	 * @param date
	 * @return 指定日期是星期几
	 */
	public static String getWeekOfDate(Date date) {
	    String[] weekDays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
	    Calendar cal = Calendar.getInstance();
	    cal.setTime(date);
	    int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
	    if (w < 0)
	        w = 0;
	    return weekDays[w];
	}
	
	
	/**
	 * 给订单分配新骑手(转单)
	 * @author zxy
	 * @param inputOrder 接收参数的实体类
	 * @return 操作结果
	 */
	@ResponseBody
	@RequestMapping(value="/transfer${api.suffix}",method = {RequestMethod.POST})
	public com.xnx3.j2ee.vo.BaseVO transfer(HttpServletRequest request,Order inputOrder) {
		//对输入的的数值进行判断
		if (inputOrder.getId() == null) {
			return error("选择的订单不存在");
		}
		if(inputOrder.getQishouId() == null) {
			return error("请选择骑手");
		}
		//获取当前登录用户的id
		int id = getUserId();
		//查询要分配骑手的订单信息
		Order order = sqlService.findById(Order.class, inputOrder.getId());
		if(order == null){
			return error("要分配骑手的订单不存在");
		}
		if(order.getState().equals(Order.STATE_CANCEL) ) {
			return error("该订单已取消");
		}
		if(order.getState().equals(Order.STATE_FINISH) ) {
			return error("该订单已完成");
		}
		if (order.getQishouId().equals(inputOrder.getQishouId())) {
			return error("不能选择相同的骑手");
		}
		
		//插入一条转单记录
		TransferOrderRecord transferOrderRecord = new TransferOrderRecord();
		transferOrderRecord.setCreateTime(DateUtil.timeForUnix10());
		transferOrderRecord.setOrderId(inputOrder.getId());
		transferOrderRecord.setOrderNo(order.getNo());
		//将未更新的订单骑手id和名字插入到转单记录表
		transferOrderRecord.setQishouName(order.getQishouName());
		transferOrderRecord.setQishouUserid(order.getQishouId());
		transferOrderRecord.setReason(request.getParameter("reason"));
		transferOrderRecord.setWanggeUserid(id);
		Wangge wangge = sqlService.findById(Wangge.class, id);
		if (wangge != null ) {
			transferOrderRecord.setWanggeName(wangge.getName());
		}
		//给订单分配新的骑手
		Qishou qishou = sqlService.findById(Qishou.class, inputOrder.getQishouId());
		if (qishou != null) {
			order.setQishouName(qishou.getName());
			order.setQishouId(qishou.getId());
			order.setQishouPhone(qishou.getPhone());
			order.setQishouHead(qishou.getHead());
		}
		//保存实体
		sqlService.save(order);
		//将更新之后的订单骑手名字和id插入转单记录表
		transferOrderRecord.setXinqishouName(qishou.getName());
		transferOrderRecord.setXinqishouUserid(inputOrder.getQishouId());
		//保存转单记录
		sqlService.save(transferOrderRecord);
		
		//日志记录
		ActionLogUtil.insertUpdateDatabase(request, inputOrder.getId(),"给Id为" + inputOrder.getId() + "的订单,分配新骑手，订单信息是:" + order.toString());

		return success();
	}
}
